import React, { useState, useEffect } from 'react';
import { 
  Table, Button, Form, Input, message, Modal, 
  Card, Space, Drawer, Switch, Spin, Tag, Select
} from 'antd';
import { 
  EditOutlined, DeleteOutlined, PlusOutlined, 
  ExclamationCircleOutlined,
  FolderOutlined, FileOutlined, HolderOutlined,
  CheckOutlined, CloseOutlined
} from '@ant-design/icons';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import {
  useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import './DataStructureManager.css';
import OperationNavBar from './OperationNavBar';

const { confirm } = Modal;

// API基础URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL; // 动态获取API地址

// API路径
const API_PATHS = {
  ADD_NODE: '/-/bin.directoryTree.add_directory_tree',
  GET_NODES: '/-/bin.directoryTree.get_directory_tree_by_pid',
  UPDATE_NODE: '/-/bin.directoryTree.update_directory_tree_by_id',
  DELETE_NODE: '/-/bin.directoryTree.delete_directory_node_by_id',
  UPDATE_SEQUENCE: '/-/bin.directoryTree.update_directory_sequence',
};

// 获取token（实际项目中可能从localStorage或其他地方获取）
const getToken = () => {
  return localStorage.getItem('token') || '';
};

interface TreeNodeData {
  id: string;
  name: string;
  value: string;
  pid: string;
  level: number;
  hasChildren: boolean;
  children?: TreeNodeData[];
  key: string;
}

interface DataStructureManagerProps {
  onDataChange?: (data: TreeNodeData[]) => void;
}

// 数据类型下拉选项
const DATA_TYPE_OPTIONS = [
  { label: '科学数据', value: 'spinfo' },
  { label: '原始数据', value: 'primdata' },
  { label: '工程数据', value: 'ppinfo' },
  { label: '星历数据', value: 'ephn' },
  { label: '遥测数据', value: 'ycinfo' },
  { label: '高级数据', value: 'advancedprod' },
];

// 拖拽把手组件
interface DragHandleProps {
  rowKey: string;
}

const DragHandle: React.FC<DragHandleProps> = ({ rowKey }) => {
  const {
    attributes,
    listeners,
    isDragging,
  } = useSortable({
    id: rowKey,
  });

  return (
    <div 
      style={{ display: 'inline-block' }}
      onClick={(e) => e.stopPropagation()}
      onDoubleClick={(e) => e.stopPropagation()}
    >
             <Button
         type="text"
         size="small"
         icon={<HolderOutlined />}
         className={`drag-handle ${isDragging ? 'dragging' : ''}`}
         title="拖拽排序"
         style={{ 
           cursor: isDragging ? 'grabbing' : 'grab', 
           color: '#999', 
           padding: '1px 2px',
           minWidth: 'auto',
           width: 'auto'
         }}
         {...attributes}
         {...listeners}
       />
    </div>
  );
};

// 可拖拽的表格行组件
interface DraggableRowProps extends React.HTMLAttributes<HTMLTableRowElement> {
  'data-row-key': string;
}

const DraggableRow: React.FC<DraggableRowProps> = (props) => {
  const {
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({
    id: props['data-row-key'],
  });

  const style: React.CSSProperties = {
    ...props.style,
    transform: CSS.Transform.toString(transform),
    transition,
    cursor: isDragging ? 'grabbing' : 'inherit',
    ...(isDragging ? { 
      position: 'relative', 
      zIndex: 9999,
      backgroundColor: '#f0f7ff',
      boxShadow: '0 4px 16px rgba(0, 0, 0, 0.15)',
      border: '2px solid #1890ff',
      borderRadius: '4px',
    } : {}),
  };

  const className = `${props.className || ''} ${isDragging ? 'dragging-row' : ''}`.trim();

  return (
    <tr {...props} ref={setNodeRef} style={style} className={className}>
      {props.children}
    </tr>
  );
};

const DataStructureManager: React.FC<DataStructureManagerProps> = ({ onDataChange }) => {
  const [form] = Form.useForm();
  const [treeData, setTreeData] = useState<TreeNodeData[]>([]);
  const [tableData, setTableData] = useState<TreeNodeData[]>([]);
  const [selectedNode, setSelectedNode] = useState<TreeNodeData | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [editMode, setEditMode] = useState<boolean>(false);
  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState<string>('');
  const [currentPid, setCurrentPid] = useState<string>('0'); // 默认父节点ID
  
  // 分页状态管理
  const [pageSize, setPageSize] = useState<number>(10); // 默认10条
  const [currentPage, setCurrentPage] = useState<number>(1); // 当前页码
  
  // 内联编辑状态管理
  const [editingCell, setEditingCell] = useState<{
    id: string;
    field: 'name' | 'value';
    value: string;
  } | null>(null);

  // 拖拽传感器配置
  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 8,
      },
    }),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  // 移除未使用的导航相关变量

  // API调用函数
  const callApi = async (url: string, data: any) => {
    const token = getToken();
    try {
      const response = await fetch(`${API_BASE_URL}${url}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'token': token
        },
        body: JSON.stringify(data)
      });
      
      if (!response.ok) {
        throw new Error(`API调用失败: ${response.statusText}`);
      }
      
      return await response.json();
    } catch (error: any) {
      console.error(`API调用错误: ${url}`, error);
      message.error(`API错误: ${error.message}`);
      throw error;
    }
  };

  // 更新节点排序
  const updateNodeSequence = async (sequenceData: { id: number; sequence: number }[]) => {
    setLoading(true);
    try {
      const token = getToken();
      const response = await fetch(`${API_BASE_URL}${API_PATHS.UPDATE_SEQUENCE}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'token': token
        },
        body: JSON.stringify(sequenceData)
      });
      
      if (!response.ok) {
        throw new Error(`排序更新失败: ${response.statusText}`);
      }
      
      const result = await response.json();
      if (result && (result.code === 0 || result.code === 200)) {
        message.success('节点排序更新成功!');
        return true;
      } else {
        message.error(`排序更新失败: ${result.msg || '未知错误'}`);
        return false;
      }
    } catch (error: any) {
      console.error('更新节点排序失败:', error);
      message.error(`排序更新错误: ${error.message}`);
      return false;
    } finally {
      setLoading(false);
    }
  };

  // 处理拖拽结束事件
  const handleDragEnd = async (event: DragEndEvent) => {
    const { active, over } = event;

    if (!over || active.id === over.id) {
      return;
    }

    const flatData = getFlatTableData(tableData);
    const oldIndex = flatData.findIndex((item) => item.key === active.id);
    const newIndex = flatData.findIndex((item) => item.key === over.id);

    if (oldIndex === -1 || newIndex === -1) {
      return;
    }

    // 检查是否在同一父节点下拖拽
    const activeItem = flatData[oldIndex];
    const overItem = flatData[newIndex];
    
    if (activeItem.pid !== overItem.pid) {
      message.warning('只能在同一父节点下进行排序!');
      return;
    }

    // 获取同一父节点下的所有节点
    const sameParentNodes = flatData.filter(item => item.pid === activeItem.pid);
    const activeIndexInParent = sameParentNodes.findIndex(item => item.key === active.id);
    const overIndexInParent = sameParentNodes.findIndex(item => item.key === over.id);
    
    if (activeIndexInParent === -1 || overIndexInParent === -1) {
      return;
    }

    // 立即更新本地状态以提供即时反馈
    const updateLocalTreeData = (nodes: TreeNodeData[]): TreeNodeData[] => {
      return nodes.map(node => {
        // 如果这个节点就是需要重新排序的父节点
        if (node.children && node.children.some(child => child.pid === activeItem.pid)) {
          // 获取当前子节点列表
          const childrenInSameParent = node.children.filter(child => child.pid === activeItem.pid);
          const otherChildren = node.children.filter(child => child.pid !== activeItem.pid);
          
          // 应用排序
          const activeChildIndex = childrenInSameParent.findIndex(child => child.key === active.id);
          const overChildIndex = childrenInSameParent.findIndex(child => child.key === over.id);
          
          if (activeChildIndex !== -1 && overChildIndex !== -1) {
            const reorderedChildren = arrayMove(childrenInSameParent, activeChildIndex, overChildIndex);
            return {
              ...node,
              children: [...reorderedChildren, ...otherChildren]
            };
          }
        }
        
        // 如果当前节点是根级别且需要排序的是根级别节点
        if (!node.children && node.pid === activeItem.pid) {
          return node;
        }
        
        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          return { ...node, children: updateLocalTreeData(node.children) };
        }
        
        return node;
      });
    };

    // 如果是根级别的排序，直接对tableData进行排序
    let updatedTableData: TreeNodeData[];
    if (activeItem.pid === '' || activeItem.pid === '0') {
      // 根级别排序
      const rootNodes = tableData.filter(node => node.pid === activeItem.pid);
      const activeRootIndex = rootNodes.findIndex(node => node.key === active.id);
      const overRootIndex = rootNodes.findIndex(node => node.key === over.id);
      
      if (activeRootIndex !== -1 && overRootIndex !== -1) {
        updatedTableData = arrayMove(tableData, activeRootIndex, overRootIndex);
      } else {
        updatedTableData = tableData;
      }
    } else {
      // 非根级别排序，使用递归更新
      updatedTableData = updateLocalTreeData(tableData);
    }

    // 更新本地状态
    setTableData(updatedTableData);

    // 生成排序数据 - 基于重新排序后的同一父节点下的节点
    const newFlatData = getFlatTableData(updatedTableData);
    const newSameParentNodes = newFlatData.filter(item => item.pid === activeItem.pid);
    const sequenceData = newSameParentNodes.map((item, index) => ({
      id: parseInt(item.id),
      sequence: index + 1
    }));

    // 调用排序API
    const success = await updateNodeSequence(sequenceData);
    
    if (success) {
      // 静默重新加载完整目录树以确保数据一致性
      await loadCompleteDirectoryTree(false);
    } else {
      // 如果API失败，恢复原始状态
      setTableData(tableData);
    }
  };

  // 获取扁平化的表格数据（用于拖拽排序）
  const getFlatTableData = (data: TreeNodeData[]): TreeNodeData[] => {
    const result: TreeNodeData[] = [];
    
    const flatten = (nodes: TreeNodeData[]) => {
      nodes.forEach(node => {
        result.push(node);
        if (node.children && node.children.length > 0) {
          flatten(node.children);
        }
      });
    };
    
    flatten(data);
    return result;
  };

  // 根据展开状态过滤应该显示的节点（用于分页支持）
  const getVisibleTableData = (data: TreeNodeData[], expandedKeys: React.Key[]): TreeNodeData[] => {
    const flatData = getFlatTableData(data);
    const visibleData: TreeNodeData[] = [];
    
    flatData.forEach(node => {
      // 根节点总是显示
      if (node.level === 0) {
        visibleData.push({ ...node, children: undefined }); // 移除children属性以启用分页
        return;
      }
      
      // 检查所有父级节点是否都已展开
      let shouldShow = true;
      let currentPid = node.pid;
      
      while (currentPid && currentPid !== '' && currentPid !== '0') {
        const parentNode = flatData.find(n => n.id === currentPid);
        if (!parentNode) break;
        
        if (!expandedKeys.includes(parentNode.key)) {
          shouldShow = false;
          break;
        }
        
        currentPid = parentNode.pid;
      }
      
      if (shouldShow) {
        visibleData.push({ ...node, children: undefined }); // 移除children属性以启用分页
      }
    });
    
    return visibleData;
  };

  // 将API返回的数据转换为表格可用的树形结构
  const convertApiDataToTableData = (apiData: any[], parentLevel: number = 0): TreeNodeData[] => {
    return apiData.map(item => {
      const node: TreeNodeData = {
        id: item.id.toString(),
        name: item.name,
        value: item.value || '',
        pid: item.pid === '0' ? '' : item.pid.toString(),
        level: parentLevel,
        hasChildren: item.children && item.children.length > 0,
        key: item.id.toString(),
      };
      
      // 递归处理子节点
      if (item.children && item.children.length > 0) {
        node.children = convertApiDataToTableData(item.children, parentLevel + 1);
      }
      
      return node;
    });
  };

  // 从树形数据中获取搜索结果（保持树形结构）
  const searchInTreeData = (treeData: TreeNodeData[], searchValue: string): TreeNodeData[] => {
    const result: TreeNodeData[] = [];
    
    const filterNode = (node: TreeNodeData): TreeNodeData | null => {
      const nodeMatches = node.name.toLowerCase().includes(searchValue.toLowerCase()) ||
                         node.value.toLowerCase().includes(searchValue.toLowerCase());
      
      let filteredChildren: TreeNodeData[] = [];
      
      // 如果有子节点，递归过滤子节点
      if (node.children && node.children.length > 0) {
        filteredChildren = node.children
          .map(child => filterNode(child))
          .filter(child => child !== null) as TreeNodeData[];
      }
      
      // 如果当前节点匹配或有匹配的子节点，则包含该节点
      if (nodeMatches || filteredChildren.length > 0) {
        return {
          ...node,
          children: filteredChildren.length > 0 ? filteredChildren : undefined
        };
      }
      
      return null;
    };
    
    treeData.forEach(node => {
      const filteredNode = filterNode(node);
      if (filteredNode) {
        result.push(filteredNode);
      }
    });
    
    return result;
  };

  // 获取树形数据的总节点数（用于统计显示）
  const getTreeNodeCount = (treeData: TreeNodeData[]): number => {
    let count = 0;
    
    const countNodes = (nodes: TreeNodeData[]) => {
      nodes.forEach(node => {
        count++;
        if (node.children && node.children.length > 0) {
          countNodes(node.children);
        }
      });
    };
    
    countNodes(treeData);
    return count;
  };

  // 获取需要展开的节点keys（递归获取所有有子节点的节点）
  const getExpandableKeys = (nodes: TreeNodeData[]): React.Key[] => {
    const keys: React.Key[] = [];
    
    const traverse = (nodeList: TreeNodeData[]) => {
      nodeList.forEach(node => {
        if (node.children && node.children.length > 0) {
          keys.push(node.key);
          traverse(node.children);
        }
      });
    };
    
    traverse(nodes);
    return keys;
  };

  // 递归加载所有数据
  const loadAllDirectoryTree = async (): Promise<TreeNodeData[]> => {
    const loadNodeAndChildren = async (pid: string = '0'): Promise<TreeNodeData[]> => {
      try {
        const result = await callApi(API_PATHS.GET_NODES, { pid });
        if (result && result.data && Array.isArray(result.data)) {
          const nodes: TreeNodeData[] = [];
          
          for (const item of result.data) {
            const node: TreeNodeData = {
              id: item.id.toString(),
              name: item.name,
              value: item.val || '',
              pid: item.pid === '0' ? '' : item.pid.toString(),
              level: 0, // 将在后面重新计算
              hasChildren: false, // 将在加载子节点后更新
              key: item.id.toString(),
            };
            
            // 递归加载子节点
            const children = await loadNodeAndChildren(item.id.toString());
            if (children.length > 0) {
              node.children = children;
              node.hasChildren = true;
            }
            
            nodes.push(node);
          }
          
          return nodes;
        }
        return [];
      } catch (error) {
        console.error(`加载节点 ${pid} 的数据失败:`, error);
        return [];
      }
    };
    
    return await loadNodeAndChildren('0');
  };

  // 重新计算节点层级
  const recalculateNodeLevels = (nodes: TreeNodeData[], level: number = 0): TreeNodeData[] => {
    return nodes.map(node => {
      const updatedNode = {
        ...node,
        level
      };
      
      if (node.children) {
        updatedNode.children = recalculateNodeLevels(node.children, level + 1);
      }
      
      return updatedNode;
    });
  };

  // 加载完整的目录树数据
  const loadCompleteDirectoryTree = async (showLoadingMessage: boolean = true) => {
    setLoading(true);
    try {
      if (showLoadingMessage) {
        // message.info('正在递归加载所有数据，请稍候...');
      }
      
      const allTreeData = await loadAllDirectoryTree();
      
      if (allTreeData.length > 0) {
        // 重新计算层级
        const treeDataWithLevels = recalculateNodeLevels(allTreeData);
        
        setTreeData(treeDataWithLevels);
        setTableData(treeDataWithLevels);
        
        // 清空搜索状态
        setSearchValue('');
        
        if (showLoadingMessage) {
          // message.success(`成功加载 ${getTreeNodeCount(treeDataWithLevels)} 个节点的完整目录树!`);
        }
        
                 // 默认全部收起
         setExpandedRowKeys([]);
        
        // 通知父组件数据变更
        onDataChange && onDataChange(treeDataWithLevels);
        
        return true;
      } else {
        if (showLoadingMessage) {
          message.warning('未找到任何目录树数据');
        }
        setTreeData([]);
        setTableData([]);
        setSearchValue('');
        return false;
      }
    } catch (error) {
      console.error('加载完整目录树失败:', error);
      message.error('加载完整目录树失败!');
      setTreeData([]);
      setTableData([]);
      setSearchValue('');
      return false;
    } finally {
      setLoading(false);
    }
  };

  // 加载目录树数据
  const loadDirectoryTree = async (pid: string = '0') => {
    setLoading(true);
    try {
      const result = await callApi(API_PATHS.GET_NODES, { pid });
      if (result && result.data) {
        // 将API返回的数据转换为表格数据格式
        const treeNodes = convertApiDataToTableData(result.data);
        setTreeData(treeNodes);
        
        // 直接使用树形数据，不进行扁平化
        setTableData(treeNodes);
        
        // 清空搜索状态
        setSearchValue('');
        
                 setCurrentPid(pid);
         // message.success('目录树数据加载成功!');
         
         // 默认全部收起
         setExpandedRowKeys([]);
        
        // 通知父组件数据变更
        onDataChange && onDataChange(treeNodes);
      } else {
        message.warning('未找到目录树数据或数据为空');
        setTreeData([]);
        setTableData([]);
        setSearchValue('');
      }
    } catch (error) {
      console.error('加载目录树失败:', error);
      setTreeData([]);
      setTableData([]);
      setSearchValue('');
    } finally {
      setLoading(false);
    }
  };

  // 添加节点到目录树
  const addDirectoryNode = async (name: string, value: string, pid: string) => {
    setLoading(true);
    try {
      const result = await callApi(API_PATHS.ADD_NODE, { name, value, pid });
      if (result && (result.code === 0 || result.code === 200)) {
        // message.success('节点添加成功!');
        // 重新加载完整目录树
        await loadCompleteDirectoryTree();
        return true;
      } else {
        message.error(`添加节点失败: ${result.msg || '未知错误'}`);
        return false;
      }
    } catch (error) {
      console.error('添加节点失败:', error);
      return false;
    } finally {
      setLoading(false);
    }
  };

  // 更新目录树节点
  const updateDirectoryNode = async (id: string, name: string, value: string) => {
    setLoading(true);
    try {
      const result = await callApi(API_PATHS.UPDATE_NODE, { id, name, value });
      if (result && (result.code === 0 || result.code === 200)) {
        message.success('节点更新成功!');
        // 重新加载完整目录树
        await loadCompleteDirectoryTree();
        return true;
      } else {
        message.error(`更新节点失败: ${result.msg || '未知错误'}`);
        return false;
      }
    } catch (error) {
      console.error('更新节点失败:', error);
      return false;
    } finally {
      setLoading(false);
    }
  };

  // 删除目录树节点
  const deleteDirectoryNode = async (id: string) => {
    setLoading(true);
    try {
      const result = await callApi(API_PATHS.DELETE_NODE, { id });
      if (result && (result.code === 0 || result.code === 200)) {
        message.success('节点删除成功!');
        // 重新加载完整目录树
        await loadCompleteDirectoryTree();
        return true;
      } else {
        message.error(`删除节点失败: ${result.msg || '未知错误'}`);
        return false;
      }
    } catch (error) {
      console.error('删除节点失败:', error);
      return false;
    } finally {
      setLoading(false);
    }
  };

  // 初始加载
  useEffect(() => {
    loadCompleteDirectoryTree();
  }, []);

  // 修改 saveInlineEdit 支持传入 customValue
  const saveInlineEdit = async (customValue?: string) => {
    if (!editingCell) return;
    const { id, field } = editingCell;
    const value = typeof customValue === 'string' ? customValue : editingCell.value;
    // 验证输入
    if (!value.trim()) {
      message.error('输入内容不能为空');
      return;
    }
    try {
      setLoading(true);
      // 找到要编辑的节点
      const findNode = (nodes: TreeNodeData[]): TreeNodeData | null => {
        for (const node of nodes) {
          if (node.id === id) return node;
          if (node.children) {
            const found = findNode(node.children);
            if (found) return found;
          }
        }
        return null;
      };
      const targetNode = findNode(treeData);
      if (!targetNode) {
        message.error('找不到目标节点');
        setEditingCell(null);
        return;
      }
      // 准备更新数据
      const updateData = {
        name: field === 'name' ? value.trim() : targetNode.name,
        value: field === 'value' ? value.trim() : targetNode.value
      };
      // 调用更新API
      const success = await updateDirectoryNode(id, updateData.name, updateData.value);
      if (success) {
        setEditingCell(null);
        message.success('更新成功');
      } else {
        message.error('更新失败，请重试');
      }
    } catch (error) {
      console.error('内联编辑保存失败:', error);
      message.error('保存失败，请重试');
    } finally {
      setLoading(false);
    }
  };
  
  // 取消内联编辑
  const cancelInlineEdit = () => {
    setEditingCell(null);
  };

  // 更新节点数据
  const updateNodeData = async (values: any) => {
    if (!selectedNode) return;
    
    try {
      // 如果是更新现有节点
      if (selectedNode.id && selectedNode.id !== 'temp') {
        await updateDirectoryNode(
          selectedNode.id,
          values.name,
          values.value
        );
      } 
      // 如果是新增节点
      else {
        await addDirectoryNode(
          values.name,
          values.value,
          values.pid || currentPid
        );
      }
      
      // 重新加载完整数据树
      await loadCompleteDirectoryTree();
      setDrawerVisible(false);
      setSelectedNode(null);
    } catch (error) {
      console.error('节点数据更新失败:', error);
      message.error('节点数据更新失败!');
    }
  };

  // 提交表单
  const handleFormSubmit = (values: any) => {
    updateNodeData(values);
  };

  // 添加新节点
  const addNewNode = (parentId: string | null = null) => {
    let parentLevel = -1;
    if (parentId) {
      // 在treeData中查找parentId对应的节点，获取其level
      const findParentLevel = (nodes: TreeNodeData[]): number => {
        for (const node of nodes) {
          if (node.id === parentId) return node.level;
          if (node.children) {
            const childLevel = findParentLevel(node.children);
            if (childLevel !== -1) return childLevel;
          }
        }
        return -1;
      };
      parentLevel = findParentLevel(treeData);
    }
    const newNode: TreeNodeData = {
      id: 'temp',
      name: '',
      value: '',
      pid: parentId || currentPid,
      level: parentLevel === -1 ? 0 : parentLevel + 1,
      hasChildren: false,
      key: 'temp',
    };
    
    // 选中新节点并打开编辑抽屉
    setSelectedNode(newNode);
    form.setFieldsValue({
      id: newNode.id,
      name: newNode.name,
      value: newNode.value,
      pid: newNode.pid,
    });
    setDrawerVisible(true);
    setEditMode(true);
  };

  // 编辑节点
  const editNode = (record: TreeNodeData) => {
    setSelectedNode(record);
    form.setFieldsValue({
      id: record.id,
      name: record.name,
      value: record.value,
      pid: record.pid,
    });
    setDrawerVisible(true);
    setEditMode(true);
  };

  // 删除节点
  const deleteNode = (nodeId: string) => {
    confirm({
      title: '确定要删除此节点吗？',
      icon: <ExclamationCircleOutlined />,
      content: '如果该节点包含子节点，所有子节点也将被删除。此操作不可撤销。',
      onOk: async () => {
        try {
          await deleteDirectoryNode(nodeId);
          
          if (selectedNode && selectedNode.id === nodeId) {
            setSelectedNode(null);
            setDrawerVisible(false);
          }
        } catch (error) {
          console.error('删除节点失败:', error);
        }
      },
    });
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchValue(value);
    
         if (!value.trim()) {
       // 重置为原始树形数据
       setTableData(treeData);
       // 重置展开状态为全部收起
       setExpandedRowKeys([]);
       return;
     }
    
    // 搜索匹配的节点
    const filteredData = searchInTreeData(treeData, value);
    setTableData(filteredData);
    
    // 搜索时展开所有匹配的节点
    const expandKeys = getExpandableKeys(filteredData);
    setExpandedRowKeys(expandKeys);
  };


  // 动态获取节点名称label和placeholder
  const getNameLabelAndPlaceholder = () => {
    if (!selectedNode) return { label: '节点名称', placeholder: '请输入节点名称' };
    if (selectedNode.level === 0) {
      return { label: '任务名称', placeholder: '请输入任务名称' };
    } else if (selectedNode.level === 1) {
      return { label: '数据类型', placeholder: '请输入数据类型' };
    } else {
      return { label: '载荷源包/数据名称', placeholder: '请输入载荷源包/数据名称' };
    }
  };

  // 动态获取节点值label和placeholder
  const getValueLabelAndPlaceholder = () => {
    if (!selectedNode) return { label: '节点值', placeholder: '请输入节点值' };
    if (selectedNode.level === 0) {
      return { label: '任务代号', placeholder: '请输入任务代号' };
    } else if (selectedNode.level === 1) {
      return { label: '数据类型代号', placeholder: '请输入数据类型代号' };
    } else {
      return { label: '载荷代号', placeholder: '请输入载荷代号' };
    }
  };

  // 内联编辑组件
  const InlineEditCell: React.FC<{
    record: TreeNodeData;
    field: 'name' | 'value';
    children: React.ReactNode;
  }> = ({ record, field, children }) => {
    const isEditing = editingCell?.id === record.id && editingCell?.field === field;
    const [isComposing, setIsComposing] = useState(false); // 添加输入法状态
    
    // L1层的名称不允许编辑
    const canEdit = !(field === 'name' && record.level === 1);
    
    const handleDoubleClick = (e: React.MouseEvent) => {
      // 防止事件冒泡
      e.stopPropagation();
      
      // 防止在拖拽手柄上触发编辑
      if ((e.target as HTMLElement).closest('.drag-handle')) {
        return;
      }
      
      if (!canEdit || loading) return;
      
      const currentValue = field === 'name' ? record.name : record.value;
      setEditingCell({
        id: record.id,
        field,
        value: currentValue
      });
    };
    
    const handleKeyPress = (e: React.KeyboardEvent) => {
      if (isComposing) {
        return;
      }
      if (e.key === 'Enter') {
        const inputValue = (e.target as HTMLInputElement).value;
        if (editingCell) {
          setEditingCell({
            ...editingCell,
            value: inputValue
          });
        }
        saveInlineEdit(inputValue);
      } else if (e.key === 'Escape') {
        cancelInlineEdit();
      }
    };
    
    const handleBlur = (e: React.FocusEvent) => {
      if (isComposing) {
        return;
      }
      const relatedTarget = e.relatedTarget as HTMLElement;
      if (relatedTarget && relatedTarget.closest('.inline-edit-buttons')) {
        return;
      }
      const inputValue = (e.target as HTMLInputElement).value;
      setTimeout(() => {
        if (!isComposing && editingCell?.id === record.id && editingCell?.field === field) {
          if (editingCell) {
            setEditingCell({
              ...editingCell,
              value: inputValue
            });
          }
          saveInlineEdit(inputValue);
        }
      }, 150);
    };
    
    // 处理输入法开始事件
    const handleCompositionStart = () => {
      setIsComposing(true);
    };
    
    // 处理输入法结束事件
    const handleCompositionEnd = () => {
      setIsComposing(false);
    };
    
    const handleSaveClick = (e: React.MouseEvent) => {
      const inputElement = (e.currentTarget as HTMLElement).parentElement?.parentElement?.querySelector('input');
      if (inputElement && editingCell) {
        setEditingCell({
          ...editingCell,
          value: inputElement.value
        });
        setTimeout(() => {
          saveInlineEdit(inputElement.value);
        }, 0);
      }
    };
    
    if (isEditing) {
      return (
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          gap: 4,
          width: '100%',
          minWidth: 0,
          flex: 1
        }}>
          <Input
            defaultValue={field === 'name' ? record.name : record.value}
            onKeyDown={handleKeyPress}
            onBlur={handleBlur}
            onCompositionStart={handleCompositionStart}
            onCompositionEnd={handleCompositionEnd}
            autoFocus
            size="small"
            style={{ flex: 1, minWidth: 0 }}
          />
          <div className="inline-edit-buttons" style={{ display: 'flex', gap: 2, flexShrink: 0 }}>
            <Button
              type="text"
              size="small"
              icon={<CheckOutlined />}
              onClick={handleSaveClick}
              style={{ color: '#52c41a', padding: '0 4px' }}
              title="保存"
            />
            <Button
              type="text"
              size="small"
              icon={<CloseOutlined />}
              onClick={cancelInlineEdit}
              style={{ color: '#ff4d4f', padding: '0 4px' }}
              title="取消"
            />
          </div>
        </div>
      );
    }
    
    return (
      <div
        onDoubleClick={handleDoubleClick}
        style={{
          cursor: canEdit && !loading ? 'pointer' : 'default',
          padding: '4px 8px',
          borderRadius: '4px',
          transition: 'background-color 0.2s',
          minHeight: '22px',
          display: 'flex',
          alignItems: 'center'
        }}
        className={canEdit && !loading ? 'inline-edit-cell' : ''}
        title={canEdit && !loading ? '双击编辑' : (field === 'name' && record.level === 1 ? '此层级需要在侧边栏编辑' : '')}
      >
        {children}
      </div>
    );
  };

  // 获取层级标签样式
  const getLevelTagStyle = (level: number) => {
    const colors = {
      0: { color: '#1890ff', bg: '#e6f7ff', border: '#91d5ff' }, // 蓝色 - 任务层
      1: { color: '#52c41a', bg: '#f6ffed', border: '#b7eb8f' }, // 绿色 - 数据类型层
      2: { color: '#fa8c16', bg: '#fff7e6', border: '#ffd591' }, // 橙色 - 数据层
      3: { color: '#722ed1', bg: '#f9f0ff', border: '#d3adf7' }, // 紫色 - 更深层级
    };
    const defaultColor = { color: '#595959', bg: '#f5f5f5', border: '#d9d9d9' };
    return colors[level as keyof typeof colors] || defaultColor;
  };

  // 表格列定义
  const columns = [
    {
      title: '节点名称',
      dataIndex: 'name',
      key: 'name',
      width: 400,
      render: (text: string, record: TreeNodeData) => {
        const levelStyle = getLevelTagStyle(record.level);
        return (
          <Space size={4}>
            <DragHandle rowKey={record.key} />
            <InlineEditCell record={record} field="name">
              <Space size={6} style={{ alignItems: 'center' }}>
                <span style={{ display: 'flex', alignItems: 'center' }}>
                  {record.hasChildren ? <FolderOutlined /> : <FileOutlined />}
                  <span 
                    style={{ 
                      marginLeft: 8,
                      fontWeight: record.level === 0 ? 600 : record.level === 1 ? 500 : 400,
                      fontSize: record.level === 0 ? '14px' : '13px',
                      color: record.level === 0 ? '#262626' : record.level === 1 ? '#434343' : '#595959'
                    }}
                  >
                    {text || '未命名节点'}
                  </span>
                </span>
                <Tag 
                  style={{ 
                    margin: 0,
                    padding: '0 6px',
                    fontSize: '11px',
                    lineHeight: '18px',
                    height: '18px',
                    color: levelStyle.color,
                    backgroundColor: levelStyle.bg,
                    borderColor: levelStyle.border,
                    borderRadius: '9px',
                    fontWeight: 500
                  }}
                >
                  L{record.level}
                </Tag>
              </Space>
            </InlineEditCell>
          </Space>
        );
      },
    },
    {
      title: '节点值',
      dataIndex: 'value',
      key: 'value',
      width: 350,
      render: (text: string, record: TreeNodeData) => (
        <InlineEditCell record={record} field="value">
          <span style={{ 
            color: text ? '#666' : '#ccc',
            fontStyle: text ? 'normal' : 'italic',
            fontSize: '13px'
          }}>
            {text || '无值'}
          </span>
        </InlineEditCell>
      ),
    },
    {
      title: '节点ID',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '父节点ID',
      dataIndex: 'pid',
      key: 'pid',
      width: 100,
      render: (text: string) => text || '根节点',
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: any, record: TreeNodeData) => (
        <Space>
          {record.level !== 1 && (
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => editNode(record)}
              size="small"
            >
              编辑
            </Button>
          )}
          <Button
            type="text"
            icon={<PlusOutlined />}
            onClick={() => addNewNode(record.id)}
            size="small"
          >
            添加子节点
          </Button>
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => deleteNode(record.id)}
            size="small"
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];


  return (
    <div className="data-structure-manager" style={{ 
      background: 'linear-gradient(to bottom, #ffffff 0%, #f0f7ff 50%, #e6f0ff 100%)', 
      minHeight: '100vh',
      padding: '0'
    }}>
      {/* 运行管理导航条 */}
      <OperationNavBar />
      
      {loading && (
        <div className="global-loading">
          <Spin size="large" tip="数据处理中，请稍候..." />
        </div>
      )}
      
      <div style={{ padding: '0 24px 24px 24px' }}>
        <Card className="header-card">
          <Space size="large" wrap>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => addNewNode()}
            disabled={loading}
          >
            添加根节点
          </Button>

          
          <Space>
            <Button
              type="primary"
              onClick={() => {
                const allKeys = getExpandableKeys(tableData);
                setExpandedRowKeys(allKeys);
              }}
              disabled={loading || tableData.length === 0}
            >
              展开全部
            </Button>
            <Button
              type="primary"
              onClick={() => setExpandedRowKeys([])}
              disabled={loading || tableData.length === 0}
            >
              收起全部
            </Button>
          </Space>
          
          <Input.Search
            placeholder="搜索节点名称或值"
            value={searchValue}
            onChange={e => handleSearch(e.target.value)}
            onSearch={handleSearch}
            style={{ 
              width: 280,
              '--ant-input-padding-horizontal': '8px',
              '--ant-input-padding-vertical': '4px'
            }}
            styles={{
              input: {
                border: 'none',
                boxShadow: 'none',
                padding: '4px 8px'
              }
            }}
            allowClear
          />
          
          <Tag color="blue">
            当前显示: {getTreeNodeCount(tableData)} 个节点
          </Tag>
        </Space>
        </Card>
        
        <Card className="content-card">
        <DndContext
          sensors={sensors}
          collisionDetection={closestCenter}
          onDragEnd={handleDragEnd}
        >
          <SortableContext
            items={getFlatTableData(tableData).map(item => item.key)}
            strategy={verticalListSortingStrategy}
          >
            <Table
              columns={columns}
              dataSource={getVisibleTableData(tableData, expandedRowKeys)}
              rowKey="key"
              pagination={{
                current: currentPage,
                pageSize: pageSize,
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '50', '100'],
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                showQuickJumper: true,
                onChange: (page, size) => {
                  setCurrentPage(page);
                  if (size && size !== pageSize) {
                    setPageSize(size);
                  }
                },
                onShowSizeChange: (_, size) => {
                  setCurrentPage(1); // 改变页面大小时重置到第一页
                  setPageSize(size);
                }
              }}
              scroll={{ x: 'max-content' }}
              bordered
              size="middle"
                             expandable={{
                 expandedRowKeys,
                 onExpandedRowsChange: (keys) => setExpandedRowKeys([...keys]),
                 indentSize: 40,
                expandIcon: ({ expanded, onExpand, record }) => {
                  if (!record.hasChildren) return <span style={{ width: 16, display: 'inline-block' }} />;
                  return (
                    <span
                      onClick={e => onExpand(record, e)}
                      style={{
                        cursor: 'pointer',
                        width: 16,
                        height: 16,
                        display: 'inline-flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        borderRadius: '2px',
                        backgroundColor: expanded ? '#1890ff' : '#f0f0f0',
                        color: expanded ? '#fff' : '#666',
                        fontSize: '10px',
                        fontWeight: 'bold',
                        transition: 'all 0.2s'
                      }}
                      title={expanded ? '收起' : ''}
                    >
                      {expanded ? '−' : '+'}
                    </span>
                  );
                }
              }}
              components={{
                body: {
                  row: DraggableRow,
                },
              }}
              rowClassName={(record, index) => {
                const baseClass = record.hasChildren ? 'table-row-folder' : 'table-row-file';
                const levelClass = `table-row-level-${record.level}`;
                const zebraClass = index % 2 === 0 ? 'table-row-even' : 'table-row-odd';
                return `${baseClass} ${levelClass} ${zebraClass}`;
              }}
              loading={loading}
            />
          </SortableContext>
        </DndContext>
      </Card>
      
      <Drawer
        title={selectedNode && selectedNode.id !== 'temp' ? '编辑节点' : '添加节点'}
        placement="right"
        width={400}
        onClose={() => {
          setDrawerVisible(false);
          setEditMode(false);
          setSelectedNode(null);
        }}
        open={drawerVisible}
        extra={
          <Space>
            <Switch
              checkedChildren="编辑模式"
              unCheckedChildren="查看模式"
              checked={editMode}
              onChange={setEditMode}
            />
          </Space>
        }
        footer={
          editMode && (
            <div style={{ textAlign: 'right' }}>
              <Button 
                onClick={() => {
                  setDrawerVisible(false);
                  setEditMode(false);
                  setSelectedNode(null);
                }} 
                style={{ marginRight: 8 }}
              >
                取消
              </Button>
              <Button 
                type="primary" 
                onClick={() => form.submit()}
                loading={loading}
              >
                保存
              </Button>
            </div>
          )
        }
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleFormSubmit}
          disabled={!editMode}
          onValuesChange={(changed) => {
            // L1层级时，name变化自动同步value
            if (selectedNode?.level === 1 && changed.name) {
              const found = DATA_TYPE_OPTIONS.find(opt => opt.label === changed.name);
              if (found) {
                form.setFieldsValue({ value: found.value });
              }
            }
          }}
        >
          <Form.Item
            name="id"
            label="节点ID"
          >
            <Input disabled />
          </Form.Item>
          
          <Form.Item
            name="name"
            label={getNameLabelAndPlaceholder().label}
            rules={[{ required: true, message: `请输入${getNameLabelAndPlaceholder().label}` }]}
          >
            {selectedNode?.level === 1 ? (
              <Select
                placeholder="请选择数据类型"
                options={DATA_TYPE_OPTIONS.map(opt => ({ label: opt.label, value: opt.label }))}
                showSearch
                filterOption={(input, option) =>
                  (option?.label as string).toLowerCase().includes(input.toLowerCase())
                }
              />
            ) : (
              <Input placeholder={getNameLabelAndPlaceholder().placeholder} />
            )}
          </Form.Item>
          
          <Form.Item 
            name="value" 
            label={getValueLabelAndPlaceholder().label}
            rules={[{ required: true, message: `请输入${getValueLabelAndPlaceholder().label}` }]}
          >
            {selectedNode?.level === 1 ? (
              <Input
                placeholder="数据类型代号会自动联动"
                disabled
              />
            ) : (
              <Input.TextArea 
                placeholder={getValueLabelAndPlaceholder().placeholder} 
                autoSize={{ minRows: 2, maxRows: 6 }}
              />
            )}
          </Form.Item>
          
          <Form.Item
            name="pid"
            label="父节点ID"
          >
            <Input placeholder={`默认使用当前PID: ${currentPid}`} />
          </Form.Item>
        </Form>
      </Drawer>
      </div>
    </div>
  );
};

export default DataStructureManager; 